package com.zjs.thread.lock;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description 锁的使用
 * @Author zhu_jinsheng[zhu_js@suixingpay.com]
 * @Date 2019/12/26 15:42
 * @Version 1.0
 */
public class LockDemo {
    private static int num = 100;
    //使用synchronized
    public synchronized void pessimismMethodS(String currentThread){
        //同步内容
    }
    //使用ReentrantLock（重入锁）
    private static ReentrantLock lock = new ReentrantLock(); //需要保证多个线程使用同一个锁
    public void pessimismMethodR(String currentThread){
        lock.lock();
        //操作同步资源
        try {
            Thread.sleep(500);
            if (num >= 0) {
                System.out.println(currentThread + "持有锁!---" + num--);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        lock.unlock();
    }
    //---------------乐观锁---------------
    private AtomicInteger atomicInteger = new AtomicInteger(); //需要保证多个线程使用同一个AtomicInteger
    public void optimisticLock(String currentThread){
        try {
            Thread.sleep(500);
            System.out.println(currentThread + "---" + atomicInteger.incrementAndGet());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
